<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate" size="small">添加</el-button>
      <el-input class="filter-item" v-model="listQuery.id" placeholder="渠道ID" clearable
                style="width: 220px" size="small"/>
      <el-input class="filter-item" v-model="listQuery.name" placeholder="渠道名称" clearable
                style="width: 220px" size="small"/>

      <el-button class="filter-item" icon="el-icon-search" :loading="listLoading" type="primary"
                 @click="handleFilter" size="small">搜索
      </el-button>
    </div>
    <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        size="small"
    >
      <el-table-column align="center" label="渠道ID" width="95">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="渠道名称" min-width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="渠道全称" min-width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.full_name }}
        </template>
      </el-table-column>
      <el-table-column label="联系电话" min-width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.contact_phone }}
        </template>
      </el-table-column>
      <el-table-column label="联系邮箱" min-width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.contact_email }}
        </template>
      </el-table-column>
      <el-table-column label="历史佣金" min-width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.channel_commission }}
        </template>
      </el-table-column>
      <el-table-column label="待付款佣金" min-width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.not_pay_channel_commission }}
        </template>
      </el-table-column>
<!--      <el-table-column label="备注" min-width="110" align="center">-->
<!--        <template slot-scope="scope">-->
<!--          {{ scope.row.remark }}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column align="center" prop="created_at" label="创建时间" min-width="140">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="更新时间" min-width="140">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.updated_at }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">修改</el-button>
<!--          <el-button size="mini" type="danger" @click="handleDel(scope.row.id)">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                     :total="total" background layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="form" :rules="rules" :model="form" label-position="left" label-width="90px"
               style="width: 400px; margin-left:50px;">
        <el-form-item  label="渠道名称" prop="name">
          <el-input v-model="form.name"/>
        </el-form-item>
        <el-form-item  label="渠道全称" prop="full_name">
          <el-input v-model="form.full_name"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="contact_phone">
          <el-input v-model="form.contact_phone"/>
        </el-form-item>
        <el-form-item label="联系邮箱" prop="contact_email">
          <el-input v-model="form.contact_email"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveData" :loading="btnLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import request from '@/utils/request'

export default {
  data() {
    return {
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      form: {
        id: '',
        name: undefined,
        full_name: undefined,
        contact_phone: undefined,
        contact_email: undefined,
      },
      rules: {
        name: [{required: true, message: '客户名称不能为空', trigger: 'blur'}],
        full_name: [{required: true, message: '客户全称不能为空', trigger: 'blur'}],
        contact_phone: [{required: true, message: '联系电话不能为空', trigger: 'blur'}],
        contact_email: [{required: true, message: '联系邮箱不能为空', trigger: 'blur'}],
      },
      btnLoading: false,

      show: false,
      imgBase64Data: '', // the datebase64 url of created image
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      request({
        url: '/api/backend/channel/list',
        method: 'get',
        params: this.listQuery
      }).then(response => {
        this.list = response.data.data
        this.total = response.data.total
      }).finally(() => {
        this.listLoading = false;
      })
    },
    handleFilter() {
      console.log(this.listQuery)
      this.listQuery.page = 1
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetForm() {
      this.form = {
        id: '',
        app_id: '',
        api_key: '',
        status: 'enable'
      }
      this.btnLoading = false
    },

    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.resetForm()
      this.form = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    saveData() {

      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.btnLoading = true
          request({
            url: '/api/backend/channel/store',
            method: 'post',
            data: this.form
          }).then(response => {
            this.btnLoading = false
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
            this.getList();
          }).catch((err) => {
            this.btnLoading = false
          })
        }
      })
    },
    handleDel(val) {
      this.$confirm('确定要删除, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        request({
          url: '/api/backend/api-account/delete',
          method: 'post',
          data: {id: val}
        }).then(() => {
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },

    toggleShow() {
      this.show = !this.show;
    },
    cropSuccess(imgBase64Data, field) {
      console.log('-------- 裁剪成功 --------');
      let that = this;
      this.imgBase64Data = imgBase64Data;
      getQiniuToken().then(response => {
        let file = base64toFile(imgBase64Data, 'tmp.png')
        let key = guid() + '.png';
        let token = response.data.token
        let baseUrl = response.data.baseUrl
        let putExtra = {}
        let config = {
          useCdnDomain: true,
          region: qiniu.region.z2
        };
        var observable = qiniu.upload(file, key, token, putExtra, config)
        var subscription = observable.subscribe({
          next(res) {
            // ...
          },
          error(err) {
            // ...
          },
          complete(res) {
            // ...
            let imgUrl = baseUrl + '/' + key;
            that.form.img = imgUrl
            console.log(imgUrl)
          }
        }) // 上传开始
        // or
        // var subscription = observable.subscribe(next, error, complete) // 这样传参形式也可以
        // subscription.unsubscribe() // 上传取消
      })

    },
  }
}
</script>


<style>
.upload-block {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}

.uploaded-img {
  width: 120px;
  height: 120px;
}

.upload-block:hover {
  border-color: #409EFF;
}

.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
</style>
